#!/bin/bash

# 装机指南 API 服务器端部署脚本
echo "🚀 开始在服务器上部署装机指南 API..."

# 设置变量
DOMAIN="api.xlcig.cn"
PROJECT_DIR="/opt/xlcig-api"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

warn() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING: $1${NC}"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
}

# 检查是否为 root 用户
check_root() {
    if [ "$EUID" -ne 0 ]; then
        error "请使用 root 用户运行此脚本"
        exit 1
    fi
    log "Root 权限检查通过"
}

# 检查 Docker 是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        log "正在安装 Docker..."
        curl -fsSL https://get.docker.com | sh
        systemctl start docker
        systemctl enable docker
        log "Docker 安装完成"
    else
        log "Docker 已安装"
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log "正在安装 Docker Compose..."
        curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
        chmod +x /usr/local/bin/docker-compose
        log "Docker Compose 安装完成"
    else
        log "Docker Compose 已安装"
    fi
}

# 检查必要文件
check_files() {
    log "检查必要文件..."
    
    required_files=(
        "dist/app.js"
        "package.json"
        "Dockerfile.server"
        "docker-compose.server.yml"
        "nginx.conf"
    )
    
    for file in "${required_files[@]}"; do
        if [ ! -f "$file" ]; then
            error "缺少必要文件: $file"
            exit 1
        fi
    done
    
    log "所有必要文件检查通过"
}

# 创建必要目录
create_directories() {
    log "创建必要目录..."
    mkdir -p logs/nginx
    mkdir -p ssl
    chmod 755 logs
    chmod 755 ssl
    log "目录创建完成"
}

# 停止现有服务
stop_services() {
    log "停止现有服务..."
    docker-compose -f docker-compose.server.yml down 2>/dev/null || true
    log "现有服务已停止"
}

# 构建并启动服务
start_services() {
    log "构建并启动服务..."
    docker-compose -f docker-compose.server.yml up -d --build
    if [ $? -eq 0 ]; then
        log "服务启动成功"
    else
        error "服务启动失败"
        docker-compose -f docker-compose.server.yml logs
        exit 1
    fi
}

# 检查服务状态
check_services() {
    log "检查服务状态..."
    sleep 15
    
    # 检查 API 健康状况
    for i in {1..5}; do
        if curl -f http://localhost:9999/health &> /dev/null; then
            log "API 服务运行正常"
            return 0
        fi
        warn "第 $i 次检查失败，5秒后重试..."
        sleep 5
    done
    
    error "API 服务启动失败"
    docker-compose -f docker-compose.server.yml logs api
    exit 1
}

# 配置防火墙
configure_firewall() {
    log "配置防火墙..."
    
    # 检查是否有 ufw
    if command -v ufw &> /dev/null; then
        ufw allow 80/tcp
        ufw allow 443/tcp
        ufw allow 9999/tcp
        log "UFW 防火墙规则已设置"
    # 检查是否有 firewalld
    elif command -v firewall-cmd &> /dev/null; then
        firewall-cmd --permanent --add-port=80/tcp
        firewall-cmd --permanent --add-port=443/tcp
        firewall-cmd --permanent --add-port=9999/tcp
        firewall-cmd --reload
        log "Firewalld 防火墙规则已设置"
    else
        warn "未检测到防火墙，请手动开放端口 80, 443, 9999"
    fi
}

# 显示部署信息
show_deployment_info() {
    log "部署完成！"
    echo ""
    echo -e "${BLUE}🎉 装机指南 API 服务器端部署成功！${NC}"
    echo ""
    echo -e "${YELLOW}服务信息：${NC}"
    echo "• API 地址: https://${DOMAIN}"
    echo "• 健康检查: https://${DOMAIN}/health"
    echo "• 本地端口: http://localhost:9999"
    echo ""
    echo -e "${YELLOW}管理命令：${NC}"
    echo "• 查看日志: docker-compose -f docker-compose.server.yml logs -f"
    echo "• 重启服务: docker-compose -f docker-compose.server.yml restart"
    echo "• 停止服务: docker-compose -f docker-compose.server.yml down"
    echo "• 查看状态: docker-compose -f docker-compose.server.yml ps"
    echo ""
    echo -e "${YELLOW}下一步操作：${NC}"
    echo "• 配置域名解析：将 ${DOMAIN} 解析到此服务器 IP"
    echo "• 配置 SSL 证书：运行 ./ssl-setup.sh 自动配置"
    echo ""
}

# 主执行流程
main() {
    log "开始服务器端部署流程..."
    
    check_root
    check_docker
    check_files
    create_directories
    configure_firewall
    stop_services
    start_services
    check_services
    show_deployment_info
    
    log "服务器端部署流程完成！"
}

# 执行主函数
main "$@" 